package com.cqc.androidzinglibrary01;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;

/**
 * Created by cui on 2017/9/16.
 */

public class CustomScanActivity extends AppCompatActivity {

    private Button btn_light;
    private boolean isOpen = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        CaptureFragment fragment = new CaptureFragment();
        CodeUtils.setFragmentArgs(fragment, R.layout.my_camera);
        fragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_scan, fragment).commit();

        btn_light = (Button) findViewById(R.id.btn_light);
        btn_light.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isOpen) {
                    CodeUtils.isLightEnable(false);
                    isOpen = false;
                    btn_light.setText("打开闪光灯");
                } else {
                    CodeUtils.isLightEnable(true);
                    isOpen = true;
                    btn_light.setText("关闭闪光灯");
                }
            }
        });
    }


    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
            bundle.putString(CodeUtils.RESULT_STRING, result);
            resultIntent.putExtras(bundle);
            CustomScanActivity.this.setResult(RESULT_OK, resultIntent);
            CustomScanActivity.this.finish();
        }


        @Override
        public void onAnalyzeFailed() {
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
            bundle.putString(CodeUtils.RESULT_STRING, "");
            resultIntent.putExtras(bundle);
            CustomScanActivity.this.setResult(RESULT_OK, resultIntent);
            CustomScanActivity.this.finish();
        }
    };
}
